<template>
  <div class="order-container">
    <!-- 侧边导航 -->
    <aside class="sidebar">
      <div class="sidebar-header">
        <i class="el-icon-house" style="margin-right: 8px"></i>
        订单管理
      </div>
      <el-menu
          v-model:default-active="statusSelected"
          class="el-menu-vertical-demo"
          @select="handleMenuSelect"
      >
        <el-menu-item index="0">
          <i class="el-icon-s-order"></i>
          <span>待支付</span>
        </el-menu-item>
        <el-menu-item index="1">
          <i class="el-icon-success"></i>
          <span>已支付</span>
        </el-menu-item>
        <el-menu-item index="2">
          <i class="el-icon-s-tools"></i>
          <span>发货</span>
        </el-menu-item>
        <el-menu-item index="3">
          <i class="el-icon-s-check"></i>
          <span>已完成</span>
        </el-menu-item>
      </el-menu>
    </aside>

    <!-- 主内容区 -->
    <main class="main-content">
      <!-- 订单表格 -->
      <el-table
          :data="tableData"
          border
          style="width: 100%; margin-top: 20px"
          :loading="tableLoading"
          stripe
          :row-class-name="tableRowClassName"
      >
        <el-table-column prop="order_no" label="订单号" width="360" />
        <!-- 支付类型映射：0-支付宝、1-微信、2-银行卡 -->
        <el-table-column prop="pay_type" label="支付类型" width="150">
          <template #default="scope">
            <el-tag :type="getPayTypeTag(scope.row.pay_type)">
              {{ payTypeMap[scope.row.pay_type] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="total_amount" label="支付金额" width="150">
          <template #default="scope">
            <span class="text-primary font-medium">
              ¥{{ scope.row.total_amount.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <!-- 日期格式化：使用 dayjs 处理 -->
        <el-table-column prop="create_time" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="pay_time" label="支付时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.pay_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="delivery_time" label="发货时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.delivery_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <!-- 简化：直接传递行数据，不做深拷贝 -->
            <el-dropdown
                @command="(cmd) => handleAction(cmd, scope.row)"
                placement="bottom"
            >
              <span class="el-dropdown-link cursor-pointer text-primary">
                更多操作<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                      command="detail"
                      icon="el-icon-view"
                  >
                    详情
                  </el-dropdown-item>
                  <el-dropdown-item
                      command="delete"
                      icon="el-icon-delete"
                      class="text-danger"
                  >
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态提示 -->
      <div
          v-if="tableData.length === 0 && !tableLoading"
          class="empty-state"
      >
        <el-empty
            description="暂无当前状态的订单数据"
            image-size="120"
        />
      </div>

      <!-- 详情弹窗：独立状态，关闭按钮仅控制自身 -->
      <el-dialog
          v-model="detailDialogVisible"
          :title="dialogTitle"
          width="800px"
          destroy-on-close
          :close-on-click-modal="false"
      >
      <el-form
          :model="currentOrder"
          label-width="120px"
          size="default"
          class="detail-form"
      >
        <!-- 订单编号 -->
        <el-form-item label="订单编号">
          <el-input
              v-model="currentOrder.order_no"
              disabled
              class="order-no-input"
          />
        </el-form-item>

        <!-- 商品信息表格 -->
        <el-form-item label="商品信息">
          <el-table
              :data="currentOrder.products || []"
              border
              size="small"
              style="width: 100%"
              max-height="200"
              stripe
          >
            <el-table-column
                prop="prod_name"
                label="商品名称"
                width="220"
            />
            <el-table-column
                prop="count"
                label="数量"
                width="100"
                align="center"
            />
            <el-table-column label="单价" align="center">
              <template #default="scope">
                ¥{{ (scope.row.prod_price).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="小计" align="center">
              <template #default="scope">
                  <span class="text-primary">
                    ¥{{ ((scope.row.prod_price * scope.row.count)).toFixed(2) }}
                  </span>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <!-- 下单时间 -->
        <el-form-item label="下单时间">
          <el-input
              :value="formatDate(currentOrder.create_time)"
              disabled
          />
        </el-form-item>

        <!-- 支付时间 -->
        <el-form-item label="支付时间">
          <el-input
              :value="currentOrder.pay_time ? formatDate(currentOrder.pay_time) : '未支付'"
              disabled
          />
        </el-form-item>

        <!-- 支付方式 -->
        <el-form-item label="支付方式">
          <el-input
              :value="payTypeMap[currentOrder.pay_type] || '未选择'"
              disabled
          />
        </el-form-item>

        <!-- 收件人信息 -->
        <el-form-item label="收件人">
          <el-input
              :value="currentOrder.address?.receiver || '-'"
              disabled
          />
        </el-form-item>

        <!-- 联系电话 -->
        <el-form-item label="联系电话">
          <el-input
              :value="currentOrder.address?.phone || '-'"
              disabled
          />
        </el-form-item>

        <!-- 收货地址 -->
        <el-form-item label="收货地址">
          <el-input
              :value="currentOrder.address?.address || '-'"
              disabled
              class="address-input"
          />
        </el-form-item>

        <!-- 支付状态 -->
        <el-form-item label="支付状态">
          <el-input
              :value="statusMap[currentOrder.status] || '未知状态'"
              disabled
          />
        </el-form-item>

        <!-- 订单金额 -->
        <el-form-item label="订单金额">
          <el-input
              :value="`¥${(currentOrder.total_amount || 0).toFixed(2)}`"
              disabled
              class="amount-input"
          />
        </el-form-item>
      </el-form>

      <!-- 按订单状态动态显示按钮：逻辑清晰，互不干扰 -->
      <template #footer>
        <el-button @click="closeDetailDialog">关闭</el-button>

        <!-- 待支付（status=0）：去付款 -->
        <el-button
            type="primary"
            @click="handleGoPay"
            v-if="currentOrder.status === 0"
        >
          去付款
        </el-button>

        <!-- 已支付（status=1）或已发货（status=2）：确认收货 -->
        <el-button
            type="primary"
            @click="handleConfirmReceipt"
            v-if="currentOrder.status === 1 || currentOrder.status === 2"
        >
          确认收货
        </el-button>

        <!-- 已完成（status=3）：已收货（禁用） -->
        <el-button
            type="success"
            disabled
            v-if="currentOrder.status === 3"
        >
          已收货
        </el-button>
      </template>
      </el-dialog>

      <!-- 删除确认弹窗：独立状态，流程简化 -->
      <el-dialog
          v-model="deleteDialogVisible"
          title="确认删除"
          width="30%"
          destroy-on-close
          :close-on-click-modal="false"
      >
      <p class="delete-tip">
        您确定要删除订单
        <span class="text-primary font-medium">
            {{ deleteOrderNo }}
          </span>
        吗？此操作不可撤销！
      </p>
      <template #footer>
        <el-button @click="closeDeleteDialog">取消</el-button>
        <el-button type="danger" @click="handleDeleteConfirm">确认删除</el-button>
      </template>
      </el-dialog>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElEmpty } from 'element-plus'
import OrderApi from '@/api/order.js'
import dayjs from 'dayjs'
import ProductApi from "@/api/Product.js";

// ===================== 响应式数据：简化状态，避免冲突 =====================
const tableData = ref([])
const tableLoading = ref(false)
// 详情弹窗：独立状态+数据，关闭时重置
const detailDialogVisible = ref(false)
const dialogTitle = ref('')
const currentOrder = ref({
  id: '',
  order_no: '',
  products: [],
  address: {},
  pay_type: 0,
  total_amount: 0,
  status: 0,
  create_time: '',
  pay_time: '',
  delivery_time: ''
})
// 删除弹窗：独立状态+数据，关闭时重置
const deleteDialogVisible = ref(false)
const deleteOrderId = ref('')
const deleteOrderNo = ref('')
// 侧边栏选中状态
const statusSelected = ref('0')

// ===================== 数据映射：保持简洁 =====================
const statusMap = {
  0: '待支付',
  1: '已支付',
  2: '已发货',
  3: '已完成'
}
const payTypeMap = {
  0: '支付宝支付',
  1: '微信支付',
  2: '银行卡支付'
}

// ===================== 工具函数：功能单一 =====================
// 日期格式化
const formatDate = (date) => {
  if (!date) return '无'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 支付类型标签样式
const getPayTypeTag = (payType) => {
  const tagMap = { 0: 'success', 1: 'primary', 2: 'info' }
  return tagMap[payType] || 'default'
}

// 已完成订单行样式
const tableRowClassName = ({ row }) => {
  return row.status === 3 ? 'finished-order' : ''
}

// ===================== 接口请求：流程清晰 =====================
// 获取订单列表
const fetchOrderList = async (status) => {
  tableLoading.value = true
  try {
    const res = await OrderApi.getUserOrderList(status)
    // 直接赋值，不做额外深拷贝（后端返回数据无需修改）
    tableData.value = res.data || res
  } catch (error) {
    ElMessage.error(`获取订单失败：${error.message || '网络异常'}`)
    tableData.value = []
  } finally {
    tableLoading.value = false
  }
}

// 待支付：去付款
const handleGoPay = async () => {
  if (!currentOrder.value.id) {
    ElMessage.warning('订单ID异常，无法付款')
    return
  }
  // 1. 展示金额确认弹窗，显示当前订单需支付金额
  ElMessageBox.confirm(
      `您确定要支付当前订单吗？\n订单金额：<span class="text-primary font-medium">¥${currentOrder.value.total_amount.toFixed(2)}</span>`,
      '确认付款',
      {
        confirmButtonText: '确定付款',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true, // 允许弹窗内容使用HTML（高亮金额）
        center: true // 弹窗内容居中
      }
  ).then(async () => {
    for(let i = 0; i < currentOrder.value.products.length; i++){
      const params={
        id:currentOrder.value.products[i].prod_id,
        count:currentOrder.value.products[i].count
      }
      await ProductApi.updateStore(params)
      ElMessage.success(`成功扣除库存：${currentOrder.value.products[i].count}件`)
    }
    // 2. 用户确认后，调用付款接口
      await OrderApi.updateSetPayTime(currentOrder.value.id)
      ElMessage.success(`付款成功！已支付金额：¥${currentOrder.value.total_amount.toFixed(2)}`)
      closeDetailDialog() // 关闭详情弹窗
      await fetchOrderList(Number(statusSelected.value)) // 刷新当前状态订单列表
  }).catch(() => {
    // 3. 用户取消付款
    ElMessage.info('已取消付款操作')
  })
}

// 已支付/已发货：确认收货
const handleConfirmReceipt = async () => {
  if (!currentOrder.value.id) {
    ElMessage.warning('订单ID异常，无法确认收货')
    return
  }
  // 二次确认，避免误操作
  ElMessageBox.confirm(
      '确定要确认收货吗？确认后订单状态将更新为「已完成」',
      '确认收货',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
  ).then(async () => {
    try {
      await OrderApi.completeOrder(currentOrder.value.id)
      closeDetailDialog()
      await fetchOrderList(Number(statusSelected.value))
    } catch (error) {
      ElMessage.error(`确认收货失败：${error.message || '操作异常'}`)
    }
  }).catch(() => {
    ElMessage.info('已取消确认收货')
  })
}

// 删除订单：确认逻辑
const handleDeleteConfirm = async () => {
  if (!deleteOrderId.value) {
    ElMessage.warning('订单ID异常，无法删除')
    return
  }
  try {
    await OrderApi.deleteOrder(deleteOrderId.value)
    ElMessage.success(`订单 ${deleteOrderNo.value} 删除成功！`)
    closeDeleteDialog() // 关闭删除弹窗
    await fetchOrderList(Number(statusSelected.value)) // 刷新列表
  } catch (error) {
    ElMessage.error(`删除失败：${error.message || '操作异常'}`)
  }
}

// ===================== 事件处理：简化逻辑，避免嵌套 =====================
// 侧边栏切换状态
const handleMenuSelect = async (index) => {
  statusSelected.value = index
  await fetchOrderList(Number(index))
  ElMessage.success(`已切换至「${statusMap[Number(index)]}」订单列表`)
}

// 表格操作（详情/删除）：直接赋值，不做深拷贝
const handleAction = (command, row) => {
  if (command === 'detail') {
    // 直接赋值行数据（仅展示，不修改，无需深拷贝）
    currentOrder.value = row
    dialogTitle.value = `订单详情（${row.order_no}）`
    detailDialogVisible.value = true
  } else if (command === 'delete') {
    // 赋值删除所需数据
    deleteOrderId.value = row.id
    deleteOrderNo.value = row.order_no
    deleteDialogVisible.value = true
  }
}

// 详情弹窗：关闭+重置数据
const closeDetailDialog = () => {
  detailDialogVisible.value = false
  // 重置详情数据，避免下次打开残留旧数据
  currentOrder.value = {
    id: '',
    order_no: '',
    products: [],
    address: {},
    pay_type: 0,
    total_amount: 0,
    status: 0,
    create_time: '',
    pay_time: '',
    delivery_time: ''
  }
}

// 删除弹窗：关闭+重置数据
const closeDeleteDialog = () => {
  deleteDialogVisible.value = false
  // 重置删除数据
  deleteOrderId.value = ''
  deleteOrderNo.value = ''
}

// ===================== 页面初始化 =====================
onMounted(async () => {
  await fetchOrderList(0) // 默认加载待支付订单
})
</script>

<style scoped>
/* 整体布局 */
.order-container {
  display: flex;
  height: calc(100vh - 60px);
  background-color: #fff;
  color: #333;
  box-sizing: border-box;
}

/* 侧边栏样式 */
.sidebar {
  width: 200px;
  background: #333;
  color: #fff;
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
}
.sidebar-header {
  height: 60px;
  line-height: 60px;
  text-align: center;
  font-size: 18px;
  background: #ff7e27; /* 主色调橙色 */
  font-weight: 500;
}
.el-menu-vertical-demo {
  border-right: none;
  background: #333;
  flex: 1;
}
.el-menu-item {
  color: #fff !important;
  height: 50px;
  line-height: 50px;
  margin: 8px 0;
}
.el-menu-item.is-active {
  background: #ff7e27 !important;
  color: #fff !important;
}
.el-menu-item:hover {
  background: #444 !important;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #fafafa;
}

/* 表格样式优化 */
.el-table {
  --el-table-header-text-color: #606266;
  --el-table-row-hover-bg-color: #fff8f0; /* 橙色hover背景 */
  margin-bottom: 20px;
}
.finished-order {
  color: #909399; /* 已完成订单标灰 */
}
.el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

/* 空状态样式 */
.empty-state {
  margin: 80px 0;
  text-align: center;
  padding: 40px 0;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 详情弹窗样式 */
.detail-form {
  margin-top: 10px;
}
.order-no-input, .amount-input {
  font-weight: 500;
  color: #ff7e27 !important;
}
.address-input {
  color: #303133 !important;
}
.el-dialog__body {
  max-height: 65vh;
  overflow-y: auto;
  padding: 20px;
}
.el-form-item {
  margin-bottom: 16px;
}
.el-form-item__label {
  color: #606266;
  font-weight: 500;
}
.el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  color: #303133;
  border-color: #e4e7ed;
}

/* 删除弹窗样式 */
.delete-tip {
  color: #606266;
  line-height: 1.8;
  margin-bottom: 10px;
}
.text-primary {
  color: #ff7e27 !important;
}
.cursor-pointer {
  cursor: pointer;
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .sidebar {
    width: 180px;
  }
  .main-content {
    padding: 15px;
  }
}

@media (max-width: 992px) {
  .sidebar {
    width: 60px;
  }
  .sidebar-header {
    font-size: 0;
  }
  .el-menu-item span {
    display: none;
  }
  .el-menu-item i {
    margin-right: 0 !important;
  }
  .el-dialog {
    width: 85% !important;
  }
}

@media (max-width: 768px) {
  .order-container {
    height: calc(100vh - 40px);
  }
  .main-content {
    padding: 10px;
  }
  .el-table {
    font-size: 12px;
  }
  .el-table-column {
    width: auto !important;
  }
  .el-dialog__body {
    max-height: 55vh;
  }
  .delete-tip {
    font-size: 14px;
  }
}
</style>